import React, { useState } from 'react';
import { GeneratedReply } from '../../types';
import { GlassCard, GlassButton } from '../ui';
import { emojiGenerator, type GeneratedEmoji } from '../../services';

interface ReplyListProps {
  /** 回复列表 */
  replies: GeneratedReply[];
  /** 是否正在加载 */
  isLoading?: boolean;
  /** 复制回调 */
  onCopy?: (content: string) => void;
  /** 表情包生成回调 */
  onEmojiGenerated?: (emoji: GeneratedEmoji) => void;
}

/**
 * 回复候选列表组件
 * 展示生成的回复候选项，支持复制
 * Requirements: 1.2
 */
export const ReplyList: React.FC<ReplyListProps> = ({
  replies,
  isLoading = false,
  onCopy,
  onEmojiGenerated,
}) => {
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [showShort, setShowShort] = useState<Record<string, boolean>>({});
  const [generatingEmoji, setGeneratingEmoji] = useState<Record<string, boolean>>({});

  const handleCopy = async (reply: GeneratedReply) => {
    const content = showShort[reply.id] && reply.shortVersion 
      ? reply.shortVersion 
      : reply.content;
    
    try {
      await navigator.clipboard.writeText(content);
      setCopiedId(reply.id);
      onCopy?.(content);
      setTimeout(() => setCopiedId(null), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const toggleVersion = (id: string) => {
    setShowShort(prev => ({ ...prev, [id]: !prev[id] }));
  };

  // 根据回复内容生成表情包
  const handleGenerateEmoji = async (reply: GeneratedReply) => {
    setGeneratingEmoji(prev => ({ ...prev, [reply.id]: true }));
    try {
      const emoji = await emojiGenerator.generateFromReply(reply.content, reply.emotionalTone);
      onEmojiGenerated?.(emoji);
    } catch (error) {
      console.error('生成表情包失败:', error);
    } finally {
      setGeneratingEmoji(prev => ({ ...prev, [reply.id]: false }));
    }
  };

  const getStyleLabel = (style: string) => {
    return style === 'formal' ? '正式' : '轻松';
  };

  const getToneEmoji = (tone: string) => {
    const emojiMap: Record<string, string> = {
      happy: '😊',
      sad: '😢',
      comfort: '🤗',
      funny: '😄',
      grateful: '🙏',
      apologetic: '😔',
      neutral: '😐',
    };
    return emojiMap[tone] || '💬';
  };

  if (isLoading) {
    return (
      <div className="space-y-3">
        {[1, 2, 3].map((i) => (
          <GlassCard key={i} className="animate-pulse-soft overflow-hidden">
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <div className="h-6 w-6 bg-emerald-500/20 rounded-full animate-shimmer"></div>
                <div className="h-4 bg-emerald-500/20 rounded w-16 animate-shimmer"></div>
              </div>
              <div className="h-4 bg-emerald-500/20 rounded w-3/4 animate-shimmer" style={{ animationDelay: '0.1s' }}></div>
              <div className="h-4 bg-emerald-500/20 rounded w-1/2 animate-shimmer" style={{ animationDelay: '0.2s' }}></div>
            </div>
          </GlassCard>
        ))}
      </div>
    );
  }

  if (replies.length === 0) {
    return (
      <GlassCard className="text-center py-8">
        <p className="text-gray-500">暂无回复建议</p>
        <p className="text-gray-400 text-sm mt-1">请先输入聊天记录或选择回复目标</p>
      </GlassCard>
    );
  }

  return (
    <div className="space-y-3">
      <h3 className="text-emerald-700 text-sm font-medium mb-2">
        回复建议 ({replies.length})
      </h3>
      
      {replies.map((reply, index) => (
        <GlassCard 
          key={reply.id} 
          className="animate-slide-up"
          style={{ animationDelay: `${index * 0.1}s` } as React.CSSProperties}
        >
          <div className="flex items-start justify-between gap-3">
            <div className="flex-1 min-w-0">
              {/* 标签 */}
              <div className="flex items-center gap-2 mb-2">
                <span className="text-lg">{getToneEmoji(reply.emotionalTone)}</span>
                <span className="px-2 py-0.5 bg-emerald-100 rounded text-xs text-emerald-700">
                  {getStyleLabel(reply.style)}
                </span>
                {reply.shortVersion && (
                  <button
                    onClick={() => toggleVersion(reply.id)}
                    className="px-2 py-0.5 bg-emerald-200 rounded text-xs text-emerald-700 hover:bg-emerald-300 transition-colors"
                  >
                    {showShort[reply.id] ? '完整版' : '精简版'}
                  </button>
                )}
              </div>
              
              {/* 内容 */}
              <p className="text-gray-700 text-sm leading-relaxed break-words">
                {showShort[reply.id] && reply.shortVersion 
                  ? reply.shortVersion 
                  : reply.content}
              </p>
            </div>
            
            {/* 操作按钮 */}
            <div className="flex flex-col gap-2 flex-shrink-0">
              <GlassButton
                size="sm"
                onClick={() => handleCopy(reply)}
              >
                {copiedId === reply.id ? (
                  <span className="text-emerald-600">✓ 已复制</span>
                ) : (
                  <span>复制</span>
                )}
              </GlassButton>
              <GlassButton
                size="sm"
                onClick={() => handleGenerateEmoji(reply)}
                disabled={generatingEmoji[reply.id]}
              >
                {generatingEmoji[reply.id] ? '⏳' : '🎨 表情'}
              </GlassButton>
            </div>
          </div>
        </GlassCard>
      ))}
    </div>
  );
};

export default ReplyList;
